<template>
    <view :class="['tip-container', isDarkMode ? 'dark-mode' : '']">
        <view class="header">
            <text class="header-title">我的日程</text>
        </view>
        <view class="calendar-container">
            <Calendar class="calendar" :initial-date="selectedDate" :date="selectedDate"
                :marked-dates="calendarMarkedDates" @select="onDateSelect" @monthChange="onMonthChange">
                <template v-for="(count, date) in todoCountMap" :key="date">
                    <view v-if="Number(count) > 0" class="todo-indicator" :slot="date">
                        <image style="width: 20px;height: 20px;"
                            src="https://s1.chu0.com/src/img/png/d9/d9d431d6537a46c9b13ecb392d80cbe4.png?imageMogr2/auto-orient/thumbnail/!132x132r/gravity/Center/crop/132x132/quality/85/%7CimageView2/2/w/132&e=2051020800&token=1srnZGLKZ0Aqlz6dk7yF4SkiYf4eP-YrEOdM1sob:KAxm4A_BCK6VG_VeFoxKRfEBa3U="
                            mode="aspectFit"></image>
                        <text class="todo-count">{{ count }}</text>
                    </view>
                </template>
            </Calendar>
        </view>

        <!-- 待办事项列表 -->
        <view class="todo-list">
            <view class="todo-header">
                <text class="todo-title">提醒事项</text>
                <button class="add-btn bigfont big-jia" @click="showAddTodo"></button>
            </view>
            <view class="todo-items">
                <template v-if="currentDayTodos.length > 0">
                    <view v-for="todo in currentDayTodos" :key="todo.id" class="todo-item">
                        <view class="todo-content">
                            <view class="todo-main">
                                <text class="todo-title">{{ todo.title }}</text>
                                <text class="todo-amount" v-if="todo.amount !== undefined">{{ todo.amount.toFixed(2)
                                    }}</text>
                            </view>
                            <view class="todo-detail" v-if="todo.notes || todo.needReminder || todo.location">
                                <view class="todo-info">
                                    <view v-if="todo.notes || todo.remark" class="remark-wrapper"
                                        :class="{ 'expanded': expandedNotes[String(todo.id || '')] }"
                                        @click.stop="toggleNotes(String(todo.id || ''))">
                                        <text class="remark"
                                            :class="{ 'expanded': expandedNotes[String(todo.id || '')] }">{{
                                                todo.notes ||
                                                todo.remark }}</text>
                                        <text class="bigfont big-youjiantoucu"
                                            v-if="isNotesLong(todo.notes || todo.remark)" />
                                    </view>
                                    <view v-if="todo.location" class="location">
                                        <text class="bigfont big-location"></text>
                                        <text>{{ todo.location }}</text>
                                    </view>
                                </view>
                                <text v-if="todo.needReminder === '1'" class="reminder-tag">
                                    <text class="bigfont big-naozhong"></text>
                                    <text>已设置提醒</text>
                                </text>
                                <text v-if="todo.needReminder === '0'" class="reminder-tag warning-tag">
                                    <text>未设置提醒</text>
                                </text>
                            </view>
                        </view>
                    </view>
                </template>
                <view v-else class="no-more">
                    <text class="no-more-text">没有更多数据了</text>
                </view>
            </view>
        </view>

        <!-- 新增待办事项弹窗 -->
        <DrawerPopup v-model="showAddTodoPopup" :title="'新增待办事项'" height="80vh">
            <view class="add-todo-form">
                <view class="form-item">
                    <text class="form-label required">标题</text>
                    <input class="form-input" v-model="newTodo.title" placeholder="请输入待办事项标题" />
                </view>

                <view class="form-item">
                    <text class="form-label required">时间</text>
                    <picker mode="date" :value="newTodo.date" @change="onDateChange" class="form-picker">
                        <view class="picker-text">{{ newTodo.date || '请选择日期' }}</view>
                    </picker>
                </view>

                <view class="form-item">
                    <text class="form-label required">选择人员</text>
                    <view class="search-dropdown">
                        <view class="search-input-wrapper" @click="showPersonSelector">
                            <input class="form-input search-input" style="padding-left: 30rpx;height: 90rpx;"
                                v-model="selectedPersonName" placeholder="搜索人员" disabled />
                        </view>
                    </view>
                </view>

                <view class="form-item">
                    <text class="form-label required">金额</text>
                    <input class="form-input" type="digit" v-model="newTodo.amount" placeholder="请输入金额" />
                </view>

                <view class="form-item">
                    <text class="form-label">地点</text>
                    <input class="form-input" v-model="newTodo.location" placeholder="请输入地点（选填）" />
                </view>

                <view class="form-item">
                    <text class="form-label">是否提醒</text>
                    <view class="form-input reminder-row">
                        <text class="reminder-text">开启后将在到期时提醒</text>
                        <CustomSwitch v-model="newTodo.needReminder" @change="onReminderChange" />
                    </view>
                </view>

                <view class="form-item">
                    <text class="form-label">备注</text>
                    <textarea class="form-textarea" v-model="newTodo.notes" placeholder="请输入备注信息（选填）" />
                </view>

                <view class="form-buttons">
                    <button class="submit-btn" @click="submitTodo">确定</button>
                </view>
            </view>
        </DrawerPopup>

        <!-- 人员选择弹窗 -->
        <DrawerPopup v-model="showPersonSelectorPopup" height="50vh" position="top" :show-header="false"
            @after-enter="onDrawerAfterEnter">
            <view class="person-selector">
                <view class="search-bar">
                    <view class="search-input-container">
                        <text class="search-icon bigfont big-sousuo"></text>
                        <input class="search-input" v-model="searchText" placeholder="搜索人员" @input="onSearchInput"
                            :focus="inputFocus" :adjust-position="false" :confirm-type="'search'" />
                        <text v-if="searchText" class="clear-icon bigfont big-guanbi" @click.stop="clearSearch"></text>
                    </view>
                </view>
                <scroll-view class="person-list" scroll-y @scrolltolower="onScrollToLower" :scroll-top="scrollTop"
                    show-scrollbar="true" enhanced>
                    <view v-if="paginatedPersonnel.length > 0">
                        <view class="person-item" v-for="person in paginatedPersonnel" :key="person.id"
                            @click="selectPerson(person)">
                            <view class="person-info">
                                <text class="person-name">{{ person.name }}</text>
                                <text class="person-theme">{{ person.theme }}</text>
                                <text class="person-amount">¥{{ person.amount.toFixed(2) }}</text>
                            </view>
                        </view>
                        <view v-if="loading" class="loading-more">
                            <text class="loading-text">加载中...</text>
                        </view>
                        <view v-if="!hasMore && paginatedPersonnel.length > 0" class="no-more">
                            <text class="no-more-text">没有更多数据了</text>
                        </view>
                    </view>
                    <view v-else class="no-result">
                        <text class="no-result-text">暂无匹配结果</text>
                    </view>
                </scroll-view>
                <view class="person-selector-footer">
                    <text class="footer-title">选择人员</text>
                    <text class="close-btn bigfont big-guanbi" @click="showPersonSelectorPopup = false"></text>
                </view>
            </view>
        </DrawerPopup>
    </view>
</template>

<script setup lang="ts">
import type { GiftRecord } from '@/api/giftRecords';
import { getGiftRecordsByName } from '@/api/giftRecords';
import { addTodo, listByMonth, listByTime, updateTodoStatus, type Todo } from '@/api/todo';
import Calendar from '@/components/Calendar.vue';
import CustomSwitch from '@/components/CustomSwitch.vue';
import DrawerPopup from '@/components/DrawerPopup.vue';
import { isDarkMode } from '@/store/theme';
import { computed, onMounted, ref, watch } from 'vue';

// 格式化日期
const formatDate = (date: Date): string => {
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

const selectedDate = ref(new Date());
const todos = ref<Todo[]>([]);

// 加载待办事项列表
const loadTodoList = async (date: Date) => {
    try {
        const formattedDate = formatDate(date);
        const response = await listByTime(formattedDate);

        // 只保留当前月份的待办事项
        const currentMonth = date.getMonth();
        const currentYear = date.getFullYear();
        todos.value = response.data
            .filter(todo => {
                const todoDate = new Date(todo.date);
                return todoDate.getMonth() === currentMonth && todoDate.getFullYear() === currentYear;
            })
            .map(todo => ({
                ...todo,
                amount: typeof todo.amount === 'string' ? parseFloat(todo.amount) : todo.amount,
                status: todo.status || '0'  // 默认未完成
            }));
    } catch (error) {
        console.error('获取待办列表失败:', error);
    }
};

// 待办事项数量映射
const todoCountMap = ref<Record<string, number>>({});

// 加载月度待办事项数量
const loadMonthTodoCount = async (date: Date) => {
    try {
        const firstDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1);
        const response = await listByMonth(formatDate(firstDayOfMonth));
        if (response.code === 200) {
            todoCountMap.value = response.data;
        }
    } catch (error) {
        console.error('获取月度待办数量失败:', error);
        // 清空当前月份的数据
        todoCountMap.value = {};
    }
};

// 监听日期变化，只更新日数据
watch(selectedDate, (newDate) => {
    loadTodoList(newDate);
});

// 页面加载时获取数据
onMounted(() => {
    loadTodoList(selectedDate.value);
    loadMonthTodoCount(selectedDate.value);
});

// 按日期分组的待办事项
const todosByDate = computed(() => {
    const grouped: { [key: string]: Todo[] } = {};
    todos.value.forEach(todo => {
        if (!grouped[todo.date]) {
            grouped[todo.date] = [];
        }
        grouped[todo.date].push(todo);
    });
    return grouped;
});

// 当前选中日期的待办事项
const currentDayTodos = computed(() => {
    const date = formatDate(selectedDate.value);
    return todos.value.filter(todo => todo.date === date);
});

// 更新日历指示器的显示逻辑
const calendarMarkedDates = computed(() => {
    return Object.keys(todoCountMap.value).map(dateStr => new Date(dateStr));
});

// 切换待办事项状态
const toggleTodo = async (id: string) => {
    try {
        const todo = todos.value.find(t => t.id === id);
        if (todo) {
            const newStatus = todo.status === '1' ? 0 : 1;
            await updateTodoStatus(id, newStatus);
            // 重新加载待办列表
            loadTodoList(selectedDate.value);
            uni.showToast({
                title: '更新成功',
                icon: 'success'
            });
        }
    } catch (error) {
        console.error('更新待办状态失败:', error);
        uni.showToast({
            title: '更新失败',
            icon: 'none'
        });
    }
};

// 新增待办事项相关数据
const showAddTodoPopup = ref(false);
const showPersonSelectorPopup = ref(false);
const searchText = ref(''); // 选择人员抽屉的搜索文本
const selectedPersonName = ref(''); // 新建待办的选择人员显示文本
const newTodo = ref({
    title: '',
    date: formatDate(new Date()),
    notes: '',
    amount: '',
    personId: '',
    location: '', // 添加地点字段
    needReminder: false // 默认关闭提醒
});

// 分页相关数据
const pageSize = 10;
const currentPage = ref(1);
const loading = ref(false);
const hasMore = ref(true);

// 分页后的人员列表
const paginatedPersonnel = ref<Array<{
    id: string;
    name: string;
    theme: string;
    amount: number;
}>>([]);

// 添加输入框焦点控制
const inputFocus = ref(false);

// 添加滚动位置控制
const scrollTop = ref(0);

// 展开的备注ID集合
const expandedNotes = ref<Record<string, boolean>>({});

// 判断备注是否超过一行
const isNotesLong = (notes?: string) => {
    return notes && notes.length > 20;
};

// 切换备注展开状态
const toggleNotes = (id: string) => {
    expandedNotes.value[id] = !expandedNotes.value[id];
};

// 初始化数据
const initPersonnelData = () => {
    paginatedPersonnel.value = [];
    currentPage.value = 1;
    hasMore.value = true;
    loadMoreData();
};

// 加载更多数据
const loadMoreData = async () => {
    if (loading.value || !hasMore.value) return;

    loading.value = true;
    try {
        const response = await getGiftRecordsByName({
            name: searchText.value || '',
            pageNum: currentPage.value,
            pageSize: pageSize,
            bookId: undefined
        });

        // 处理返回的数据
        const responseData = response.data;
        if (!responseData?.records) return;

        const records = responseData.records || [];

        const mappedRecords = records.map((record: GiftRecord) => ({
            id: record.id || '',
            name: record.name,
            theme: record.books?.title || '未知礼簿',
            amount: typeof record.amount === 'string' ? parseFloat(record.amount) : record.amount
        }));

        if (mappedRecords.length > 0) {
            // 如果是第一页，直接替换数据
            if (currentPage.value === 1) {
                paginatedPersonnel.value = mappedRecords;
            } else {
                // 否则追加数据
                paginatedPersonnel.value.push(...mappedRecords);
            }

            // 更新分页信息
            currentPage.value++;
            // 判断是否还有更多数据
            hasMore.value = currentPage.value <= (responseData.totalPage || 1);
        } else {
            hasMore.value = false;
        }
    } catch (error) {
        console.error('获取人员列表失败:', error);
        uni.showToast({
            title: '获取人员列表失败',
            icon: 'none'
        });
    } finally {
        loading.value = false;
    }
};

// 监听搜索文本变化
watch(searchText, (newVal) => {
    // 如果搜索框被清空，且已有选择的人员，恢复显示已选择的人员名称
    if (!newVal && selectedPersonName.value) {
        searchText.value = selectedPersonName.value;
        return;
    }
    // 重置分页数据
    paginatedPersonnel.value = [];
    currentPage.value = 1;
    hasMore.value = true;
    scrollTop.value = 0;
    // 延迟加载数据，避免频繁请求
    setTimeout(() => {
        loadMoreData();
    }, 300);
});

// 显示添加待办事项弹窗
const showAddTodo = async () => {
    try {
        // 请求订阅消息权限

        // 显示新增弹窗
        showAddTodoPopup.value = true;
    } catch (error) {
        console.error('订阅消息失败:', error);
        uni.showToast({
            title: '订阅消息失败',
            icon: 'none'
        });
    }
};

// 监听抽屉显示状态
watch(showPersonSelectorPopup, (newVal) => {
    if (!newVal) {
        // 抽屉关闭时，重置focus状态
        inputFocus.value = false;
    }
});

// 显示人员选择器时重置数据
const showPersonSelector = () => {
    // 如果已经选择了人员，保持搜索框显示当前选择的人员名称
    if (selectedPersonName.value) {
        searchText.value = selectedPersonName.value;
    } else {
        searchText.value = '';
    }
    inputFocus.value = false;
    showPersonSelectorPopup.value = true;
    // 重置列表状态
    paginatedPersonnel.value = [];
    currentPage.value = 1;
    hasMore.value = true;
    scrollTop.value = 0;
    loadMoreData();
};

// 抽屉打开动画结束后的回调
const onDrawerAfterEnter = () => {
    // 延迟设置焦点，等待抽屉动画完成
    setTimeout(() => {
        inputFocus.value = true;
    }, 200);
};

// 选择人员
const selectPerson = (person: { id: string; name: string; theme: string; amount: number }) => {
    newTodo.value.personId = person.id;
    selectedPersonName.value = person.name; // 更新选择人员显示文本
    // 自动填充金额和标题
    newTodo.value.amount = person.amount.toString();
    newTodo.value.title = person.name;
    showPersonSelectorPopup.value = false;
};

// 搜索输入处理
const onSearchInput = () => {
    // 重新加载数据
    paginatedPersonnel.value = [];
    currentPage.value = 1;
    hasMore.value = true;
    loadMoreData();
};

// 提交表单
const submitTodo = async () => {
    // 验证必填字段
    if (!newTodo.value.title) {
        uni.showToast({ title: '请输入标题', icon: 'none' });
        return;
    }
    if (!newTodo.value.date) {
        uni.showToast({ title: '请选择日期', icon: 'none' });
        return;
    }
    if (!newTodo.value.personId) {
        uni.showToast({ title: '请选择人员', icon: 'none' });
        return;
    }
    if (!newTodo.value.amount) {
        uni.showToast({ title: '请输入金额', icon: 'none' });
        return;
    }

    try {
        uni.showLoading({ title: '保存中...' });

        const todoData = {
            title: newTodo.value.title,
            date: newTodo.value.date,
            notes: newTodo.value.notes,
            amount: parseFloat(newTodo.value.amount),
            location: newTodo.value.location, // 添加地点字段
            needReminder: newTodo.value.needReminder ? '1' : '0',
            params: {
                personId: newTodo.value.personId
            }
        };

        try {
            await addTodo(todoData);
            // 重置表单
            resetForm();
            // 重新加载待办列表
            loadTodoList(selectedDate.value);
            // 重新加载日历数据
            loadMonthTodoCount(selectedDate.value);

            uni.showToast({
                title: '添加成功',
                icon: 'success'
            });

        } catch (error: any) {
            uni.showToast({
                title: error?.msg || '添加失败',
                icon: 'none'
            });
        }
    } catch (error) {
        console.error('添加待办事项失败:', error);
        uni.showToast({
            title: '添加失败，请重试',
            icon: 'none'
        });
    } finally {
        uni.hideLoading();
    }
};

// 日期选择处理
const onDateChange = (e: any) => {
    newTodo.value.date = e.detail.value;
};

// 选择日期处理函数
const onDateSelect = (date: Date) => {
    selectedDate.value = date;
};

// 显示设置弹窗
const showSettings = () => {
    uni.showToast({
        title: '设置功能开发中',
        icon: 'none'
    });
};

// 提醒开关切换处理
const onReminderChange = async (e: any) => {
    // 先设置开关状态为false，避免出现视觉延迟
    newTodo.value.needReminder = false;

    if (e.detail.value) {
        // 如果是开启提醒，先请求订阅消息权限
        try {
            const result = await uni.requestSubscribeMessage({
                tmplIds: ['PkNDWOCSmL9LTJUlXmxdbC1uqFt7H6jUQbZAQNKcJDE']
            }) as any;

            if (result.errMsg === 'requestSubscribeMessage:ok' &&
                result['PkNDWOCSmL9LTJUlXmxdbC1uqFt7H6jUQbZAQNKcJDE'] === 'accept') {
                // 用户同意订阅，开启提醒
                newTodo.value.needReminder = true;
            } else {
                // 用户拒绝订阅，保持关闭状态
                newTodo.value.needReminder = false;
                uni.showToast({
                    title: '需要允许订阅消息才能开启提醒',
                    icon: 'none'
                });
            }
        } catch (error) {
            console.error('订阅消息失败:', error);
            newTodo.value.needReminder = false;
            uni.showToast({
                title: '订阅消息失败',
                icon: 'none'
            });
        }
    } else {
        // 关闭提醒直接执行
        newTodo.value.needReminder = false;
    }
};

// 监听滚动到底部
const onScrollToLower = () => {
    if (!loading.value && hasMore.value) {
        loadMoreData();
    }
};

// 清除搜索内容
const clearSearch = () => {
    searchText.value = '';
    // 如果之前已经选择了人员，不要清空选择的结果
    if (!selectedPersonName.value) {
        newTodo.value.personId = '';
        newTodo.value.amount = '';
        newTodo.value.title = '';
    }
    // 重新加载数据
    paginatedPersonnel.value = [];
    currentPage.value = 1;
    hasMore.value = true;
    loadMoreData();
};

// 重置表单
const resetForm = () => {
    newTodo.value = {
        title: '',
        date: formatDate(new Date()),
        notes: '',
        amount: '',
        personId: '',
        location: '', // 添加地点字段
        needReminder: false
    };
    selectedPersonName.value = ''; // 清空选择人员显示文本
    searchText.value = ''; // 清空搜索文本
    showPersonSelectorPopup.value = false;
    showAddTodoPopup.value = false;
};

// 处理月份变化
const onMonthChange = async (date: Date) => {
    // 清空待办列表
    todos.value = [];

    // 获取当前月份的第一天
    const firstDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1);

    // 判断是否是当前年月
    const now = new Date();
    const isCurrentMonth = date.getFullYear() === now.getFullYear() && date.getMonth() === now.getMonth();

    // 如果是当前年月，选中今天；否则选中1号
    if (isCurrentMonth) {
        selectedDate.value = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    } else {
        selectedDate.value = new Date(firstDayOfMonth);
    }

    try {
        // 获取月度待办数量
        const response = await listByMonth(formatDate(firstDayOfMonth));
        if (response.code === 200) {
            todoCountMap.value = response.data;
            // 加载选中日期的待办列表
            await loadTodoList(selectedDate.value);
        } else {
            uni.showToast({
                title: response.msg || '获取待办数量失败',
                icon: 'none'
            });
        }
    } catch (error) {
        console.error('获取月度待办数量失败:', error);
        todoCountMap.value = {};
        uni.showToast({
            title: '获取待办数量失败',
            icon: 'none'
        });
    } finally {
        uni.hideLoading();
    }
};
</script>

<style scoped>
.tip-container {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    height: 100vh;
    background-color: var(--theme-background);
    color: #333333;
    overflow: hidden;
    padding-top: var(--status-bar-height);
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding-bottom: constant(safe-area-inset-bottom);
    /* iOS 11.2以下版本 */
    padding-bottom: env(safe-area-inset-bottom);
    /* iOS 11.2及以上版本 */
}

.decoration-image {
    position: absolute;
    top: calc(var(--status-bar-height) + 20rpx);
    left: 20rpx;
    width: 160rpx;
    height: 120rpx;
    opacity: 0.9;
    z-index: 1;
    pointer-events: none;
}

.decoration-image image {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

.calendar-container {
    margin: 20rpx;
    background: #ffffff;
    border-radius: 24rpx;
    margin-top: 100rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.todo-indicator {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 4rpx;
}

.todo-dot {
    width: 12rpx;
    height: 12rpx;
    border-radius: 50%;
    background-color: #007AFF;
    margin-right: 4rpx;
}

.todo-count {
    font-size: 20rpx;
    color: #007AFF;
    font-weight: 600;
    background-color: white;
    padding: 2rpx 8rpx;
    border-radius: 10rpx;
    border: 1px solid #007AFF;
}

.dark-mode .todo-count {
    color: white;
    background-color: #409EFF;
    border: none;
    font-weight: 600;
}

.todo-list {
    flex: 1;
    margin: 20rpx;
    background: #ffffff;
    border-radius: 24rpx;
    padding: 30rpx;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    margin-bottom: 20rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
    position: relative;
    /* 确保内容区域不会被底部安全区域遮挡 */
    max-height: calc(100vh - var(--status-bar-height) - 44px - 40rpx - constant(safe-area-inset-bottom));
    max-height: calc(100vh - var(--status-bar-height) - 44px - 40rpx - env(safe-area-inset-bottom));
}

.todo-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    padding: 24rpx 30rpx;
    border-radius: 20rpx;
    background: #f5f7fa;
}

.todo-title {
    font-size: 30rpx;
    color: #333333;
    font-weight: 500;
    flex: 1;
    margin-right: 24rpx;
}

.add-btn {
    width: 48rpx;
    height: 48rpx;
    min-width: 48rpx;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #ffffff;
    background: var(--theme-color, #409EFF);
    border: none;
    border-radius: 16rpx;
    transition: all 0.3s ease;
    box-shadow: 0 4rpx 12rpx rgba(64, 158, 255, 0.3);
}

.add-btn:active {
    transform: scale(0.98);
    opacity: 0.8;
}

.dark-mode .add-btn {
    background: var(--theme-color, #409EFF);
    box-shadow: 0 4rpx 12rpx rgba(64, 158, 255, 0.2);
}

.todo-items {
    flex: 1;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    padding: 0 10rpx;
    padding-bottom: 40rpx;
    position: relative;
    will-change: transform;
    transform: translateZ(0);
    scroll-behavior: smooth;
}

/* 确保内容容器有足够的内边距 */
.todo-items::after {
    content: '';
    display: block;
    height: constant(safe-area-inset-bottom);
    /* iOS 11.2以下版本 */
    height: env(safe-area-inset-bottom);
    /* iOS 11.2及以上版本 */
}

/* 优化滚动条样式 */
.todo-items::-webkit-scrollbar {
    width: 6rpx;
    background-color: transparent;
}

.todo-items::-webkit-scrollbar-thumb {
    background-color: rgba(0, 0, 0, 0.1);
    border-radius: 3rpx;
    min-height: 60rpx;
    /* 确保滚动条滑块有最小高度 */
}

.todo-items::-webkit-scrollbar-track {
    background-color: transparent;
}

.dark-mode .todo-items::-webkit-scrollbar-thumb {
    background-color: rgba(255, 255, 255, 0.1);
}

.todo-item {
    display: flex;
    padding: 20rpx 24rpx;
    margin-bottom: 16rpx;
    border-radius: 16rpx;
    background: #ffffff;
    border: 1px solid #f0f0f0;
    transition: all 0.3s ease;
    position: relative;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.02);
    width: 100%;
    box-sizing: border-box;
    overflow: hidden;
}

.todo-item:active {
    transform: scale(0.98);
    background: #f9f9f9;
}

.todo-checkbox {
    margin-right: 20rpx;
    margin-top: 6rpx;
}

.todo-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 12rpx;
    width: 100%;
    overflow: hidden;
}

.todo-main {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.todo-title {
    font-size: 28rpx;
    color: #333333;
    font-weight: 500;
}

.todo-amount {
    font-size: 28rpx;
    color: #ff6b6b;
    font-weight: 600;
    padding: 4rpx 12rpx;
    background: rgba(255, 107, 107, 0.1);
    border-radius: 8rpx;
    border: 1px solid rgba(255, 107, 107, 0.2);
}

.todo-amount::before {
    content: '¥';
    margin-right: 2rpx;
    font-size: 24rpx;
}

.todo-detail {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 12rpx;
    width: 100%;
}

.todo-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 12rpx;
    min-width: 0;
    overflow: hidden;
}

.gift-info {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.gift-details {
    display: flex;
    flex-direction: column;
    gap: 8rpx;
}

.remark-wrapper {
    position: relative;
    background-color: rgba(64, 158, 255, 0.05);
    padding: 6rpx 12rpx;
    padding-right: 48rpx;
    border-radius: 8rpx;
    cursor: pointer;
    width: 100%;
    box-sizing: border-box;
    display: flex;
    align-items: flex-start;
    overflow: hidden;
    min-height: 36rpx;
    transition: all 0.3s ease;
    border: 1px solid rgba(64, 158, 255, 0.1);
}

.remark {
    font-size: 22rpx;
    color: var(--theme-color, #409EFF);
    line-height: 1.4;
    flex: 1;
    min-width: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    transition: all 0.3s ease;
    opacity: 0.8;
}

.remark.expanded {
    white-space: normal;
    text-overflow: clip;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: none;
    max-height: none;
}

.remark-wrapper.expanded {
    height: auto;
    padding: 12rpx;
    padding-right: 48rpx;
}

.remark-wrapper .big-youjiantoucu {
    position: absolute;
    right: 12rpx;
    top: 50%;
    transform: translateY(-50%) rotate(0deg);
    font-size: 22rpx;
    color: var(--theme-color, #409EFF);
    width: 28rpx;
    height: 28rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: transform 0.3s ease;
    opacity: 0.8;
}

.remark-wrapper.expanded .big-youjiantoucu {
    transform: translateY(-50%) rotate(90deg);
}

.reminder-tag {
    display: flex;
    align-items: center;
    gap: 6rpx;
    font-size: 22rpx;
    color: var(--theme-color, #409EFF);
    background: rgba(64, 158, 255, 0.15);
    padding: 6rpx 12rpx;
    border-radius: 8rpx;
    flex-shrink: 0;
    margin-left: 12rpx;
    white-space: nowrap;
    height: 36rpx;
    box-sizing: border-box;
}

.reminder-tag .bigfont {
    font-size: 22rpx;
    color: var(--theme-color, #409EFF);
}

.location {
    display: flex;
    align-items: center;
    gap: 6rpx;
    font-size: 22rpx;
    color: #999;
    margin-top: 6rpx;
}

.location .bigfont {
    font-size: 22rpx;
}

/* 暗黑模式样式 */
.dark-mode {
    background-color: #1a1a1a;
    color: #ffffff;
}

.dark-mode .todo-list {
    background-color: #2a2a2a;
    box-shadow: none;
}

.dark-mode .todo-header {
    background: rgba(255, 255, 255, 0.05);
}

.dark-mode .todo-item {
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.1);
    box-shadow: none;
}

.dark-mode .todo-item:active {
    background: rgba(255, 255, 255, 0.08);
}

.dark-mode .todo-title {
    color: #ffffff;
}

.dark-mode .todo-notes {
    color: rgba(255, 255, 255, 0.5);
}

.dark-mode .header {
    background-color: #1a1a1a;
    box-shadow: none;
}

.dark-mode .header-title {
    color: #ffffff;
}

/* 自定义 checkbox 样式 */
.todo-item checkbox {
    transform: scale(0.9);
    margin-right: 8rpx;
}

.header {
    position: fixed;
    top: var(--status-bar-height);
    left: 0;
    right: 0;
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 32rpx;
    z-index: 100;
}

.header-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333333;
}

.header-right {
    display: flex;
    align-items: center;
}

.header-btn {
    background: none;
    border: none;
    padding: 16rpx 24rpx;
    margin: 0;
    line-height: 1;
}

.header-btn-text {
    font-size: 28rpx;
    color: #666;
}

.dark-mode .header {
    background-color: #1a1a1a;
    box-shadow: none;
}

.dark-mode .header-title {
    color: #ffffff;
}

.dark-mode .header-btn-text {
    color: #999;
}

/* 表单样式优化 */
.add-todo-form {
    padding: 30rpx;
    padding-bottom: 160rpx;
    width: 100%;
    box-sizing: border-box;
    overflow-x: hidden;
    background: #fff;
}

.form-item {
    margin-bottom: 40rpx;
    position: relative;
    width: 100%;
    box-sizing: border-box;
}

.form-label {
    display: block;
    font-size: 28rpx;
    color: #666;
    margin-bottom: 16rpx;
    font-weight: 500;
    padding: 0 4rpx;
}

.form-input,
.form-textarea,
.form-picker,
.search-dropdown {
    width: 100%;
    box-sizing: border-box;
    border: none;
    border-radius: 12rpx;
    background-color: #f5f7fa;
    transition: all 0.3s ease;
    box-shadow: inset 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
}

.form-input,
.form-picker,
.search-input {
    height: 88rpx;
    padding: 0 30rpx;
    font-size: 30rpx;
    color: #333;
}

.form-textarea {
    height: 180rpx;
    padding: 24rpx 30rpx;
    font-size: 30rpx;
    color: #333;
}

.picker-text {
    height: 88rpx;
    line-height: 88rpx;
    font-size: 30rpx;
    color: #333;
}

/* 暗黑模式样式 */
.dark-mode .add-todo-form {
    background: #1a1a1a;
}

.dark-mode .form-label {
    color: rgba(255, 255, 255, 0.6);
}

.dark-mode .form-input,
.dark-mode .form-textarea,
.dark-mode .form-picker,
.dark-mode .search-dropdown {
    background-color: #2a2a2a;
    color: #fff;
}

.dark-mode .form-input::placeholder,
.dark-mode .form-textarea::placeholder {
    color: rgba(255, 255, 255, 0.3);
}

.dark-mode .picker-text {
    color: #fff;
}

.dark-mode .reminder-text {
    color: rgba(255, 255, 255, 0.6);
}

/* 表单按钮样式 */
.form-buttons {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    justify-content: center;
    padding: 20rpx 30rpx;
    background: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    z-index: 100;
    box-sizing: border-box;
    border-top: 1rpx solid #f0f0f0;
    padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
    /* iOS 11.2以下版本 */
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
    /* iOS 11.2及以上版本 */
}

.submit-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
    border-radius: 12rpx;
    font-size: 30rpx;
    font-weight: 500;
    transition: all 0.3s ease;
    background: var(--theme-color, #409EFF);
    color: #fff;
    box-shadow: 0 4rpx 12rpx rgba(64, 158, 255, 0.3);
    border: none;
}

.submit-btn:active {
    opacity: 0.9;
    transform: translateY(2rpx);
}

/* 暗黑模式按钮样式 */
.dark-mode .form-buttons {
    background: #1a1a1a;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.2);
    border-top: 1rpx solid #333;
}

.dark-mode .submit-btn {
    background: var(--theme-color, #409EFF);
    box-shadow: 0 4rpx 12rpx rgba(64, 158, 255, 0.2);
}

.required::after {
    content: '*';
    color: #ff4d4f;
    margin-left: 6rpx;
    font-weight: normal;
}

/* 滚动条美化 */
.dropdown-list::-webkit-scrollbar {
    width: 6rpx;
}

.dropdown-list::-webkit-scrollbar-track {
    background: transparent;
}

.dropdown-list::-webkit-scrollbar-thumb {
    background: #ddd;
    border-radius: 3rpx;
}

.dark-mode .dropdown-list::-webkit-scrollbar-thumb {
    background: #444;
}

.reminder-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30rpx;
    height: 88rpx;
}

.reminder-text {
    font-size: 28rpx;
    color: #666;
}

/* 自定义 switch 样式 */
.reminder-row switch {
    transform: scale(0.8);
    margin-right: -8rpx;
    color: var(--theme-color, #409EFF) !important;
}

/* 暗黑模式样式 */
.dark-mode .reminder-text {
    color: #999;
}

.dark-mode .no-result {
    background: #2a2a2a;
    color: #666;
}

.no-result {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40rpx 30rpx;
    text-align: center;
    background: transparent;
    border-radius: 12rpx;
    margin: 0;
}

.no-result-icon {
    width: 84rpx;
    height: 84rpx;
    margin-bottom: 16rpx;
    opacity: 0.8;
}

.no-result-text {
    font-size: 28rpx;
    color: #999;
    font-weight: 500;
}

/* 暗黑模式样式 */
.dark-mode .no-result {
    background: transparent;
}

.dark-mode .no-result-text {
    color: #666;
}

.dark-mode .no-result-icon {
    opacity: 0.6;
    filter: brightness(0.8);
}

.person-selector {
    display: flex;
    flex-direction: column;
    height: 100%;
    background: #fff;
    position: relative;
    border-bottom-left-radius: 24rpx;
    border-bottom-right-radius: 24rpx;
    overflow: hidden;
}

.person-list {
    flex: 1;
    height: calc(50vh - 180rpx);
    overflow-y: auto;
    padding: 0 30rpx;
    -webkit-overflow-scrolling: touch;
    /* 添加平滑滚动 */
    scroll-behavior: smooth;
    /* 添加硬件加速 */
    will-change: transform;
    transform: translateZ(0);
}

.person-item {
    padding: 24rpx 0;
    position: relative;
    transition: all 0.3s ease;
}

.person-item::after {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    height: 1rpx;
    background: #f0f0f0;
}

.person-item:last-child::after {
    display: none;
}

.person-info {
    display: grid;
    grid-template-columns: 140rpx 1fr 200rpx;
    align-items: center;
    gap: 20rpx;
}

.person-name {
    font-size: 30rpx;
    color: #333;
    font-weight: 500;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.person-theme {
    font-size: 28rpx;
    color: #666;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.person-amount {
    font-size: 28rpx;
    color: #ff6b6b;
    font-weight: 500;
    text-align: right;
    white-space: nowrap;
    padding-right: 54rpx;
}

.search-bar {
    padding: 0 30rpx;
    padding-right: 140rpx;
    background: #fff;
    position: relative;
    z-index: 10;
    height: 88rpx;
    display: flex;
    align-items: center;
}

.search-bar::after {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    height: 1rpx;
    background: #f0f0f0;
}

.search-input-container {
    position: relative;
    display: flex;
    align-items: center;
    width: 82% !important;
    height: 64rpx;
    background: #f5f7fa;
    border-radius: 32rpx;
    padding: 0 16rpx;
}

.search-icon {
    width: 32rpx;
    height: 32rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    color: #999;
    margin-right: 8rpx;
    flex-shrink: 0;
}

.clear-icon {
    width: 32rpx;
    height: 32rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    color: #999;
    margin-left: 4rpx;
    flex-shrink: 0;
    padding: 4rpx;
}

.search-input {
    flex: 1;
    height: 100%;
    font-size: 28rpx;
    color: #333;
    background: transparent;
    padding-left: 0;
    padding-right: 4rpx;
}

.search-input::placeholder {
    color: #999;
}

.person-selector-footer {
    position: relative;
    padding: 20rpx 30rpx;
    background: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    z-index: 10;
    border-bottom-left-radius: 24rpx;
    border-bottom-right-radius: 24rpx;
}

.person-selector-footer::before {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    height: 1rpx;
    background: #f0f0f0;
}

.footer-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
}

.close-btn {
    font-family: 'bigfont';
    color: #666;
    font-size: 40rpx;
}

.close-btn:active {
    opacity: 0.8;
}

.loading-more {
    padding: 20rpx 0;
    text-align: center;
    background: transparent;
}

.loading-text {
    font-size: 24rpx;
    color: #999;
}

.no-more {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    background: transparent;
    display: flex;
    align-items: center;
    justify-content: center;
    pointer-events: none;
}

.no-more-text {
    font-size: 28rpx;
    color: #999;
    position: relative;
    display: inline-block;
    padding: 0 30rpx;
    transform: translateY(-30%);
    pointer-events: none;
}

.no-more-text::before,
.no-more-text::after {
    content: '';
    position: absolute;
    top: 50%;
    width: 40rpx;
    height: 1px;
    background: #ddd;
}

.no-more-text::before {
    left: -20rpx;
}

.no-more-text::after {
    right: -20rpx;
}

/* 暗黑模式适配 */
.dark-mode .no-more {
    background: transparent;
}

.dark-mode .no-more-text {
    color: rgba(255, 255, 255, 0.5);
}

.dark-mode .no-more-text::before,
.dark-mode .no-more-text::after {
    background: rgba(255, 255, 255, 0.2);
}

/* 暗黑模式样式 */
.dark-mode .person-selector {
    background: #1a1a1a;
}

.dark-mode .person-item::after {
    background: rgba(255, 255, 255, 0.1);
}

.dark-mode .person-name {
    color: #fff;
}

.dark-mode .person-theme {
    color: rgba(255, 255, 255, 0.5);
}

.dark-mode .search-bar {
    background: #1a1a1a;
}

.dark-mode .search-bar::after {
    background: rgba(255, 255, 255, 0.1);
}

.dark-mode .search-input-container {
    background: rgba(255, 255, 255, 0.05);
}

.dark-mode .search-icon,
.dark-mode .clear-icon {
    color: rgba(255, 255, 255, 0.5);
}

.dark-mode .search-input {
    color: #fff;
}

.dark-mode .search-input::placeholder {
    color: rgba(255, 255, 255, 0.5);
}

.dark-mode .person-selector-footer {
    background: #1a1a1a;
}

.dark-mode .person-selector-footer::before {
    background: rgba(255, 255, 255, 0.1);
}

.dark-mode .footer-title {
    color: #fff;
}

.dark-mode .close-btn {
    color: rgba(255, 255, 255, 0.5);
}

.calendar {
    width: 100%;
    border-radius: 24rpx;
    overflow: hidden;
}

/* 暗黑模式样式 */
.dark-mode .remark-wrapper {
    background-color: rgba(64, 158, 255, 0.1);
    border: 1px solid rgba(64, 158, 255, 0.15);
}

.dark-mode .remark {
    color: var(--theme-color, #409EFF);
    opacity: 0.9;
}

.dark-mode .location {
    color: rgba(255, 255, 255, 0.45);
}

/* 空状态样式 */
.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60rpx 30rpx;
    height: 100%;
    box-sizing: border-box;
}

.empty-image {
    width: 240rpx;
    height: 240rpx;
    margin-bottom: 40rpx;
    opacity: 0.9;
}

.empty-text {
    font-size: 32rpx;
    color: #666;
    margin-bottom: 16rpx;
    font-weight: 500;
}

.empty-subtext {
    font-size: 28rpx;
    color: #999;
}

/* 暗黑模式空状态样式 */
.dark-mode .empty-text {
    color: rgba(255, 255, 255, 0.7);
}

.dark-mode .empty-subtext {
    color: rgba(255, 255, 255, 0.45);
}

.dark-mode .empty-image {
    opacity: 0.7;
    filter: brightness(0.8);
}

/* 添加新的CSS样式 */
.warning-tag {
    color: #ff6b6b !important;
    background: rgba(255, 107, 107, 0.15) !important;
}

.warning-tag .bigfont {
    color: #ff6b6b !important;
}

/* 暗黑模式样式 */
.dark-mode .warning-tag {
    color: #ff6b6b !important;
    background: rgba(255, 107, 107, 0.15) !important;
}

.dark-mode .warning-tag .bigfont {
    color: #ff6b6b !important;
}
</style>